package com.example.netty.ui.model

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.netty.constants.NettyConstants
import com.lu.netty.data.NettyMessageVo
import com.lu.netty.impl.BaseNettyServer
import com.lu.netty.io.core.NettyConnector
import com.lu.netty.io.core.NettyLog
import com.lu.netty.io.dispatcher.INettyServerListener
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

/**
 * FileName : ServerModel
 * Author : luqihua
 * Date : 2024/11/28
 * Desc :
 **/

class ServerModel : ViewModel(), INettyServerListener {
    companion object {
        private const val TAG = "ServerModel"
    }

    private var isServerRunning = false

    private val nettyServer by lazy {
        BaseNettyServer(NettyConstants.port).also {
            it.setListener(this)
        }
    }

    private val _clientList = MutableStateFlow<List<NettyConnector>>(arrayListOf())
    val clientList = _clientList.asStateFlow()

    fun startServer() {
        if (!isServerRunning) {
            isServerRunning = true
            nettyServer.start()
        } else {
            isServerRunning = false
            nettyServer.close()
        }
    }

    fun sendMessage(message: String) {
        viewModelScope.launch(Dispatchers.IO) {
            nettyServer.sendAll(message)
        }
    }

    fun queryClient() {
        val map = nettyServer.getClientList()
        Log.d(TAG, "queryClient: ,map=${map.size} ")
        _clientList.update { map }
    }

    override fun onClientChange(connector: NettyConnector, isAccept: Boolean) {
        if (isAccept) {
            _clientList.update { oldList ->
                val newList = ArrayList(oldList)
                if (!newList.contains(connector)) {
                    newList.add(connector)
                }
                newList
            }
        } else {
            _clientList.update { oldList ->
                val newList = ArrayList(oldList)
                newList.remove(connector)
                newList
            }
        }
    }

    override fun onRegisterChange(
        connector: NettyConnector,
        isRegister: Boolean,
        messageVo: NettyMessageVo
    ): String {
        return "收到--${connector.key}--的注册消息"
    }

    override fun onHeartbeat(connector: NettyConnector, messageVo: NettyMessageVo): String {
        return "收到--${connector.key}--心跳 : ${messageVo.message}"
    }

    override fun onContent(connector: NettyConnector, messageVo: NettyMessageVo): String {
        return "收到消息--${messageVo}"
    }

}